package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Problem;
import dao.ProblemDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/problem") // 配置请求映射路径
public class ProblemServlet extends HttpServlet {
    // jackson 核心类 用于转换json数据
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200); // 设置响应状态码
        resp.setContentType("application/json;charset=utf8");
        ProblemDao problemDao = new ProblemDao();

        // 尝试获取id如果获取到id 表示获取的是题目详细信息 反之则是题目列表
        String id = req.getParameter("id");
        if(id == null || "".equals(id)){
            List<Problem> problems = problemDao.selectAll();
            String resqString = objectMapper.writeValueAsString(problems);
            resp.getWriter().write(resqString);
        }else{
            Problem problem = problemDao.selectOne(Integer.parseInt(id));
            String resqString = objectMapper.writeValueAsString(problem);
            resp.getWriter().write(resqString);
        }
    }
}
